<?php

function getMusic() {
    $args = filter_input_array(INPUT_POST, array(
        'singer' => FILTER_DEFAULT,
        'song' => FILTER_DEFAULT
    ));
    if ($args === null || $args === array()) {
        throw new Exception('args error');
    }
    $pdo = Mysql::getInstance();
    if ($args['song'] === '') {
        $stmt = $pdo->prepare('select * from musics where singer = ?');
        $stmt->bindParam(1, $args['singer']);
    } else {
        $stmt = $pdo->prepare('select * from musics where singer = ? and song = ?');
        $stmt->bindParam(1, $args['singer']);
        $stmt->bindParam(2, $args['song']);
    }
    $stmt->execute();
    $result = $stmt->fetchAll();
    return array('musics' => $result);
}

function AddMusic() {
    $uploaddir = __DIR__ . '/../musics/';
    $name = basename($_FILES['song']['name']);
    $info = split('-', $name);
    $singer = trim($info[0]);
    $songer = split('\.', trim($info[1]));
    $song = $songer[0];
    move_uploaded_file($_FILES['song']['tmp_name'], $uploaddir . ($singer . '-' . $song . '.mp3'));
    $pdo = Mysql::getInstance();
    $stmt = $pdo->prepare('insert into musics(singer, song) values(?, ?)');
    $stmt->bindParam(1, $singer);
    $stmt->bindParam(2, $song);
    $stmt->execute();
    return array();
}

function deleteMusic() {
    $args = filter_input_array(INPUT_POST, array(
        'singer' => FILTER_DEFAULT,
        'song' => FILTER_DEFAULT
    ));
    if ($args === null || $args === array()) {
        throw new Exception('args error');
    }
    $pdo = Mysql::getInstance();
    if ($args['song'] === '') {
        $stmt = $pdo->prepare('select * from musics where singer = ?');
        $stmt->bindParam(1, $args['singer']);
    } else {
        $stmt = $pdo->prepare('select * from musics where singer = ? and song = ?');
        $stmt->bindParam(1, $args['singer']);
        $stmt->bindParam(2, $args['song']);
    }
    $stmt->execute();
    $result = $stmt->fetchAll();
    foreach ($result as $value) {
        unlink(__DIR__ . '/../musics/' . $value['singer'] . '-' . $value['song'] . '.mp3');
    }
    if ($args['song'] === '') {
        $stmt = $pdo->prepare('delete from musics where singer = ?');
        $stmt->bindParam(1, $args['singer']);
    } else {
        $stmt = $pdo->prepare('delete from musics where singer = ? and song = ?');
        $stmt->bindParam(1, $args['singer']);
        $stmt->bindParam(2, $args['song']);
    }
    $stmt->execute();
    return array();
}

try {
    $method = filter_input(INPUT_GET, 'method');
    if ($method === null) {
        throw new Exception('no method');
    }
    require __DIR__ . '/Mysql.php';
    $result = call_user_func($method);
    echo json_encode(array_merge(array('result' => true), $result));
} catch (Exception $ex) {
    echo json_encode(array('result' => false, 'msg' => $ex->getMessage()));
}